java中如何对类对象进行排序

您所在的位置:网站首页 java 数组排序sort java中如何对类对象进行排序

java中如何对类对象进行排序

2024-07-10 12:12| 来源: 网络整理| 查看: 265

        有两种方法可以实现按照类中的某一个属性(或者多个属性)来对类的对象进行排序,一种方法是类实现Comparable接口,然后调用Collections.sort(List)方法进行排序,另一种方法是类不实现Comparable接口,而在排序时使用Collections.sort(List, Comparator)方法,并实现其中的Comparator接口,或者传入一个或多个比较器对象Comparator,使用List的sort方法对对象数组进行排序。

首先创建一个简单的学生类 public class Student { private int no;//编号 private int height;//身高 private int weight;//体重 public int getNo() { return no; } public void setNo(int no) { this.no = no; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public Student(int no,int height,int weight) { this.no=no; this.height=height; this.weight=weight; } } 一、类实现Comparable接口

首先实现Comparable接口并重写compareTo()方法

public class Student implements Comparable{ private int no;//编号 private int height;//身高 private int weight;//体重 public int getNo() { return no; } public void setNo(int no) { this.no = no; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public Student(int no,int height,int weight) { this.no=no; this.height=height; this.weight=weight; } @Override public int compareTo(Object o) { Student stu = (Student)o; return this.height-stu.height;//按身高排序 //this-参数:升序;参数-this:降序 } }

接着调用Collection.sort()方法即可实现排序

public static void main(String[] args) { List stuList = new ArrayList(); stuList.add(new Student(1, 170,130)); stuList.add(new Student(2, 180,145)); Collections.sort(stuList); System.out.println(stuList); } 二、传入一个比较器对象Comparator

使用一开始的学生类,不需要实现Comparable接口

List stuList = new ArrayList(); stuList.add(new Student(1, 170,130)); stuList.add(new Student(2, 180,145)); Collections.sort(stuList, new Comparator() { @Override public int compare(Student o1, Student o2) { return o1.age - o2.age; } }); System.out.println(stuList); 依据多个字段排序

当要求先按第一个字段排序,如果第一个字段相同,则按第二个字段排序,如果第二个相同,则按第三个字段... 可以定义多个Comparator,并依次使用。

import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class sort { public static void main(String[] args) { /** * 输入 */ Scanner input = new Scanner(System.in); System.out.println("输入学生编号数量n:\n"); int n = input.nextInt(); System.out.println("输入身高序列:\n"); int[]shenGao=new int[n];//身高序列用数组记录下来 for(int i=0;i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3